package example.springboot.controller;

import example.springboot.common.Result;
import example.springboot.dto.WordDTO;
import example.springboot.entity.StudyRecord;
import example.springboot.entity.StudyTask;
import example.springboot.entity.Word;
import example.springboot.service.ErrorBookService;
import example.springboot.service.StudyRecordService;
import example.springboot.service.StudyTaskService;
import example.springboot.util.JwtUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @Author 董熠涛
 * @Date 2025/6/16 20:22
 */
@RestController
@RequestMapping("/api/study")
@CrossOrigin
public class StudyApiController {

    @Autowired
    private StudyRecordService studyRecordService;

    @Autowired
    private StudyTaskService studyTaskService;

    @Autowired
    private ErrorBookService errorBookService;

    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 获取今日学习任务
     */
    @GetMapping("/today")
    public Result<Map<String, Object>> getTodayTask(
            HttpServletRequest request,
            @RequestParam(defaultValue = "1") Integer wordbookId) {
        try {
            Integer userId = getUserIdFromRequest(request);
            if (userId == null) {
                return Result.error("未登录");
            }

            // 获取或创建今日任务
            StudyTask task = studyTaskService.getOrCreateTodayTask(userId, wordbookId);
            
            // 获取需要学习的单词
            List<Word> words = studyTaskService.getTodayTaskWords(userId, wordbookId);
            
            // 转换为DTO
            List<WordDTO> wordDTOs = words.stream().map(word -> {
                WordDTO dto = new WordDTO();
                BeanUtils.copyProperties(word, dto);
                return dto;
            }).collect(java.util.stream.Collectors.toList());
            
            Map<String, Object> result = new HashMap<>();
            result.put("taskId", task.getId());
            result.put("targetWords", task.getTargetWords());
            result.put("finishedWords", task.getFinishedWords());
            result.put("status", task.getStatus());
            result.put("words", wordDTOs);
            
            return Result.success(result);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取今日学习任务失败：" + e.getMessage());
        }
    }

    /**
     * 提交学习结果
     */
    @PostMapping("/result")
    public Result<String> submitStudyResult(
            HttpServletRequest request,
            @RequestBody Map<String, Object> data) {
        try {
            Integer userId = getUserIdFromRequest(request);
            if (userId == null) {
                return Result.error("未登录");
            }

            Integer wordId = (Integer) data.get("wordId");
            Boolean correct = (Boolean) data.get("correct");

            if (wordId == null) {
                return Result.error("单词ID不能为空");
            }
            if (correct == null) {
                return Result.error("答题结果不能为空");
            }

            // 创建学习记录
            // 注意：新表结构中不再使用 is_correct 字段，而是使用 recall_confidence
            // 这里只是创建记录，recall_confidence 应该由遗忘曲线算法计算并更新
            StudyRecord record = new StudyRecord();
            record.setUserId(userId);
            record.setWordId(wordId);
            // isCorrect 字段已移除，不再设置
            record.setLastReviewAt(new java.sql.Timestamp(System.currentTimeMillis()));  // 设置最后复习时间为当前时间
            record.setReviewCount(1);  // 设置复习次数为1
            
            studyRecordService.createStudyRecord(record);
            
            // 如果答错，添加到错题本
            if (!correct) {
                errorBookService.addOrUpdateError(userId, wordId);
            }
            
            // 更新任务进度
            studyTaskService.updateTaskProgress(userId);
            
            return Result.success("提交成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("提交学习结果失败：" + e.getMessage());
        }
    }

    /**
     * 获取复习任务
     * 返回需要复习的单词（答错的或需要复习的）
     */
    @GetMapping("/review")
    public Result<List<WordDTO>> getReviewTask(HttpServletRequest request) {
        try {
            Integer userId = getUserIdFromRequest(request);
            if (userId == null) {
                return Result.error("未登录");
            }

            // 获取错题本中的单词作为复习任务
            List<WordDTO> errorWords = errorBookService.getErrorWords(userId);
            
           
            
            return Result.success(errorWords);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取复习任务失败：" + e.getMessage());
        }
    }

    /**
     * 获取错题本
     */
    @GetMapping("/errors")
    public Result<List<WordDTO>> getErrorBook(HttpServletRequest request) {
        try {
            Integer userId = getUserIdFromRequest(request);
            if (userId == null) {
                return Result.error("未登录");
            }

            // 获取错题本中的单词
            List<WordDTO> errorWords = errorBookService.getErrorWords(userId);
            
            return Result.success(errorWords);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取错题本失败：" + e.getMessage());
        }
    }

    /**
     * 下载Anki卡片
     */
    @GetMapping("/anki")
    public Result<Map<String, String>> downloadAnki(HttpServletRequest request) {
        try {
            Integer userId = getUserIdFromRequest(request);
            if (userId == null) {
                return Result.error("未登录");
            }

        
            Map<String, String> result = new HashMap<>();
            result.put("downloadUrl", "/api/study/anki/download?userId=" + userId);
            
            return Result.success(result);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("下载Anki卡片失败：" + e.getMessage());
        }
    }

    /**
     * 从请求中获取用户ID
     */
    private Integer getUserIdFromRequest(HttpServletRequest request) {
        try {
            String token = request.getHeader("Authorization");
            if (token != null && token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
            
            if (token == null || token.isEmpty()) {
                return null;
            }

            return jwtUtil.getUserIdFromToken(token);
        } catch (Exception e) {
            return null;
        }
    }
}

